﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Core.Web.Admin.Blazor.Controllers
{
    /// <summary>
    /// 登录授权控制器
    /// </summary>
    public class AccountController : Controller
    {
        /// <summary>
        /// 登出清理Cookie
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            // 清除现有的外部Cookie
            await HttpContext
                .SignOutAsync(
                CookieAuthenticationDefaults.AuthenticationScheme);
            return Redirect("/Authorize/login");
        }
        public async Task<IActionResult> Login(string userId, string userName = "", string trueName = "", string role = "", string returnUrl = "/")
        {
            try
            {

                // *** !!! 在这里您可以验证用户 !!! ***
                // 在此示例中，我们仅登录用户（此示例始终登录用户）
                //
                var claims = new List<Claim>
             {
                 new Claim(ClaimTypes.NameIdentifier,userId),
                 new Claim(ClaimTypes.Name, userName),
                 new Claim(ClaimTypes.Surname, trueName),
                 new Claim(ClaimTypes.Role, role??"user"),
             };
                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties
                {
                    IsPersistent = true,
                    RedirectUri = this.Request.Host.Value
                };
                await HttpContext.SignInAsync(
                 CookieAuthenticationDefaults.AuthenticationScheme,
                 new ClaimsPrincipal(claimsIdentity),
                 authProperties);
            }
            catch (Exception ex)
            {
                return Redirect("/exception/500");
            }


            return Redirect(returnUrl ?? "/");
        }
    }
}
